package com.jar.exercise.多线程.Semaphore;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public class Limiter {

    private Long beginTime;

    private long period;

    private final int allCount;

    private int currentCount;

    public Limiter(int allCount, long time, TimeUnit timeUnit) {
        this.period = timeUnit.toMillis(time);
        this.allCount = allCount;
    }

    public boolean limit() {

        final long timeMillis = System.currentTimeMillis();

        if (beginTime == null) {
            beginTime = timeMillis;
            currentCount = 0;
        }

        if (timeMillis >= (beginTime + period)) {
            System.out.println("当前");
            beginTime = timeMillis;
            currentCount = 0;
            return true;
        }

        return currentCount++ < allCount;
    }


    public static void main(String[] args) throws InterruptedException {
        Limiter limiter = new Limiter(3,2 , TimeUnit.SECONDS);

        for (int i = 0; i < 100_0; i++) {
            Thread.sleep(100);
            if (limiter.limit()) {
                System.out.println(i + " : " + DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now()));
            }
        }

    }

}
